<template>
  <div>
    <template v-if="showDetail">
  <el-card>  
    <div>
      <h2>用户详情</h2>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentUser.gender === 0 ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="角色">{{ roleFormatter(currentUser.roleId) }}</el-descriptions-item>
        <el-descriptions-item label="科室">{{ departmentFormatter(currentUser.departmentId) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentUser.createTime }}</el-descriptions-item>
      </el-descriptions>
        <el-button @click="handleBack">返回</el-button>
    </div>
  </el-card>
</template>
<template v-else>
 <div>
    <el-card>
      <div class="mb-4">
        <!-- <el-button type="primary" @click="handleAdd">新增用户</el-button> -->
      </div>
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" v-if=false  label="ID" width="80" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="gender" label="性别">
          <template #default="{ row }">
            {{ row.gender === 0 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="角色">
          <template #default="{ row }">
            {{ roleFormatter(row.roleId) }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentId" label="科室">
        <template #default="{ row }">
          {{ departmentFormatter(row.departmentId) }}
        </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="handleDetail(row)">详情</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option label="管理员" :value="1" />
            <el-option label="排班员" :value="2" />
            <el-option label="医护人员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择科室">
            <el-option 
              v-for="item in departments" 
              :key="item.id" 
              :label="item.departmentName" 
              :value="item.id" />
        </el-select>
      </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  listUsertable, 
  addUsertable, 
  updateUsertable, 
  delUsertable 
} from '@/api/usertable'
import { listDepartment } from '@/api/department'
import { listRole } from '@/api/role'

const userList = ref([])
const departments = ref([])
const roles = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null)

const form = reactive({
  id: null,
  userName: '',
  password: '',
  gender: 0,
  roleId: null,
  departmentId: null
})

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 获取用户列表
const getUserList = async () => {
  try {
    const response = await listUsertable()
    if (response) {
      userList.value = response
      console.log('获取用户列表成功:', response)
    } else {
      console.error('API返回数据格式异常:', response)
      ElMessage.error('获取用户列表失败: 数据格式异常')
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    ElMessage.error(`获取用户列表失败: ${error.message}`)
  }
}
// 科室ID转名称
const departmentFormatter = (value) => {
const department = departments.value.find((item) => item.id == value)
return department ? department.departmentName : value
}

// 获取科室数据
const fetchdepartment = async () => {
  try {
    const res = await listDepartment()
    departments.value = res 
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + error.message)
  }
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  isAdd.value = true
  Object.assign(form, {
    id: null,
    userName: '',
    password: '',
    gender: 0,
    roleId: null,
    departmentId: null
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delUsertable(row.id)
    ElMessage.success('删除成功')
    getUserList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  try {
    if (isAdd.value) {
      await addUsertable(form)
      ElMessage.success('新增成功')
    } else {
      await updateUsertable(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  fetchdepartment()
  fetchRoles()
  getUserList()
})
const roleFormatter = (value) => {
  const role = roles.value.find((item) => item.id == value)
  return role ? role.roleName : value
}
const fetchRoles = async () => {
  try {
    const res = await listRole()
    roles.value = res 
  } catch (error) {
    ElMessage.error('获取角色列表失败: ' + error.message)
  }
}
const showDetail = ref(false)
const currentUser = ref(null)

const handleDetail = (row) => {
  currentUser.value = row
  showDetail.value = true
}

const handleBack = () => {
  showDetail.value = false
}
</script>